package com.sky.handler;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSException;
import com.sky.exception.BaseException;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.NoExistException;
import com.sky.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result exceptionHandler(BaseException ex){
        log.error("异常信息：{}", ex.getMessage());
        return Result.error("数据库异常");
    }

    /**
     * 捕获OSS异常
     * @param ce
     * @return
     */
    @ExceptionHandler
    public Result excpetionHandler(ClientException ce){
        System.out.println("Caught an ClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with OSS, "
                + "such as not being able to access the network.");
        System.out.println("Error Message:" + ce.getMessage());
        return Result.error("文件上传失败");
    }

    @ExceptionHandler
    public Result exceptionHandler(OSSException oe){
        System.out.println("Caught an OSSException, which means your request made it to OSS, "
                + "but was rejected with an error response for some reason.");
        System.out.println("Error Message:" + oe.getErrorMessage());
        System.out.println("Error Code:" + oe.getErrorCode());
        System.out.println("Request ID:" + oe.getRequestId());
        System.out.println("Host ID:" + oe.getHostId());
        return Result.error("文件上传失败");
    }

    @ExceptionHandler
    public Result exceptionHandler(IOException ex){
        log.info("获取字节流失败");
        log.error(ex.getMessage());
        return Result.error("文件上传失败");
    }

    //查询结果不存在
    @ExceptionHandler
    public Result exceptionHandler(NoExistException ex){
        return Result.error(ex.getMessage());
    }

    @ExceptionHandler
    public Result exceptionHandler(DeletionNotAllowedException de){
        return Result.error(de.getMessage());
    }
}
